package com.sec.bnjey.database;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.sec.bnjey.utils.RbLog;

public class DiagDbAdapter {

	private static DiagDbAdapter mAdapter;
	private DiagDbHelper mHelper;
	private SQLiteDatabase mDatabase;
	private Context mCtx;

	private DiagDbUtil diagUtil = null;
	private DiagHistoryDbUtil diagHistoryUtil = null;

	public static synchronized DiagDbAdapter getInstance(Context context) {
		if (mAdapter == null) {
			mAdapter = new DiagDbAdapter(context);
		}
		return mAdapter;
	}

	private DiagDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	public synchronized DiagDbAdapter open() throws SQLException {
		RbLog.d("DB", "open...........................");
		if (mHelper == null) {
			mHelper = new DiagDbHelper(mCtx);
			try {
				mDatabase = mHelper.getWritableDatabase();
			} catch (SQLException ex) {
				mDatabase = mHelper.getReadableDatabase();
			}
			diagUtil = new DiagDbUtil(mDatabase);
			diagHistoryUtil = new DiagHistoryDbUtil(mDatabase);
		}

		return this;
	}

	public DiagDbUtil getDiagDbUtil() {
		return diagUtil;
	}

	public DiagHistoryDbUtil getDiagHistoryDbUtil() {
		return diagHistoryUtil;
	}

	public SQLiteDatabase getDatabase() {
		return mDatabase;
	}

	public synchronized void close() {
		if (mDatabase != null) {
			mDatabase.close();
			mDatabase = null;
		}
		if (mHelper != null) {
			mHelper.close();
			mHelper = null;
		}
	}

}
